package com.jarvis.plugin.wxmock.interceptor;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.log.Log;
import com.google.inject.Inject;
import com.jarvis.plugin.wxmock.config.Constants;
import com.jarvis.plugin.wxmock.config.WxmockProperty;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import net.bytebuddy.asm.Advice.Argument;
import net.bytebuddy.asm.Advice.OnMethodEnter;
import net.bytebuddy.asm.Advice.Origin;
import okhttp3.HttpUrl;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;

/**
 * @author xuxukang
 * @create 2020/5/9 5:57 下午
 */
public class OkhttpInterceptor {
	
	@Inject
	public static WxmockProperty wxmockProperty;
	
	@OnMethodEnter
	public static void enter(@Origin Method method,
			@Argument(value = 0, readOnly = false) Request request) {
		Log.get().info("【request】{}", request);
		String url = request.url().toString();
		if (url.contains(Constants.real_wx_server_hostname)) {
			String replace = StringUtils
					.replace(url, Constants.real_wx_server_hostname, wxmockProperty.getServer());
			HttpUrl parse = HttpUrl.parse(replace);
			ReflectUtil.setFieldValue(request, "url", parse);
			Log.get().info("【info】{}", "success to replace okhttp request's httpurl");
		}
	}
	
	public static void main(String[] args) throws MalformedURLException {
		String host = new URL("http://localhost:8082").getHost();
		System.out.println(host);
	}
	
}
